package ro.ubbcluj.cs.damate.plugin.monitors;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchListener;
import org.eclipse.ui.PlatformUI;
import ro.ubbcluj.cs.damate.plugin.events.WorkspaceEvent;
import ro.ubbcluj.cs.damate.plugin.services.DamateMonitoringService;
import static ro.ubbcluj.cs.damate.plugin.utils.PluginEventConstants.*;

/**
 * Instances of this class monitor invocations of workbench start/stop.
 * 
 */
public class WorkbenchMonitor implements EventMonitor {
	
	private IWorkbenchListener workbenchListener;
	
	public void startMonitoring(final DamateMonitoringService monitoringService) {		
		this.workbenchListener = new IWorkbenchListener() {
			
			@Override
			public boolean preShutdown(IWorkbench workbench, boolean forced) {
				recordEvent(SHUTDOWN, monitoringService);
				return true;
			}
			
			@Override
			public void postShutdown(IWorkbench workbench) {
			}
		};
		recordEvent(STARTUP, monitoringService);		
		PlatformUI.getWorkbench().addWorkbenchListener(workbenchListener);		
	}

	public void stopMonitoring() {
		PlatformUI.getWorkbench().removeWorkbenchListener(workbenchListener);		
	}

	private void recordEvent(String what, final DamateMonitoringService monitoringService) {
		WorkspaceEvent event = new WorkspaceEvent();
		event.setKind(WORKBENCH);
		event.setWhat(what);
        event.addParameter(WORKSPACE, ResourcesPlugin.getWorkspace().getRoot().getLocation().toString());
		monitoringService.recordEvent(event, null, null);
	}
}
